package ProxyDemoCodes;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * <pre>
 * Created with IntelliJ IDEA.
 * User: zhengzhi
 * Date: 2017/11/24
 * Time: 16:41
 * To change this template use File | Settings | File Templates.
 * </pre>
 *
 * @author Administrator
 */
public class TwoString {
    private String s1,s2;

    private int i;

    public TwoString(){}

    public TwoString(String s1,String s2){
        this.s1 = s1;
        this.s2 = s2;
    }

    public void print(){
        System.out.println("s1:" + s1 + ",s2:" + s2 + ",i:" + i);
    }


    //通过反射增加一个字段
    public int incrementField(String filedName,Object object) throws NoSuchFieldException, IllegalAccessException {
        Field field = object.getClass().getDeclaredField(filedName);
        int value = field.getInt(object) + 1;
        field.setInt(object,value);
        return value;
    }



    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Class[] types = {String.class, String.class};

        //构造函数的反射调用
        Constructor<TwoString> cons = TwoString.class.getConstructor(types);
        Object[] argss = {"a", "b"};
        TwoString ts = cons.newInstance(argss);
        ts.print();

        //使用缺省函数创建新的实例
        TwoString ts1 = TwoString.class.newInstance();
        ts1.print();
        //将字段i的值加1
        ts1.incrementField("i",ts1);
        ts1.print();





        Field[] declaredFields = TwoString.class.getDeclaredFields();
        Field declaredFields2 = TwoString.class.getDeclaredField("s1");

        Field[] fields = TwoString.class.getFields();
//        Field s1s = TwoString.class.getField("s1");


        System.out.println(JSON.toJSONString(declaredFields));
        System.out.println(declaredFields2);
        System.out.println(JSON.toJSONString(fields));
//        System.out.println(s1s);


        Field filedI = TwoString.class.getDeclaredField("i");
        int value = filedI.getInt(TwoString.class) + 1;
        filedI.setInt(TwoString.class,value);

    }
}
